﻿/*----------------------------------------------------------------
Copyright (C) 2014 宏图会员管理系统（Grant 巩建春）

项目名称： 宏图会员管理系统
创建者：   grant (巩建春 emaill : nnn987@126.com ; QQ:406333743;Tel:+86 15619212255)
CLR版本：  4.0.30319.42000
时间：     2014/8/28 18:16:22

功能描述：本软件为本人业余时间所写，其所有源码都可以进行免费的学习交流，切勿用于商业用途

----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace Tools
{
   public static class SerializeHelper
    {
        public static string XmlSerialize<T>(T obj) where T : class
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                using (MemoryStream stream = new MemoryStream())
                {
                    serializer.Serialize(stream, obj);
                    stream.Position = 0;

                    StreamReader sr = new StreamReader(stream);
                    string resultStr = sr.ReadToEnd();
                    sr.Close();
                    stream.Close();
                    return resultStr;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public static T XmlDeserialize<T>(string xml) where T : class
        {
            T result = default(T);
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                using (MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(xml.ToCharArray())))
                {
                    result = (T)serializer.Deserialize(ms);
                    ms.Close();

                    return result;
                }
            }
            catch (Exception ex)
            {
                return result;
            }
        }
    }
}
